package com.niit.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.niit.common.Result;
import com.niit.model.Book;
import com.niit.service.BookService;
import com.niit.service.impl.BookServiceImpl;

/**
 * Servlet implementation class AddBookServlet
 */
@WebServlet("/AddBookServlet.do")
public class AddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddBookServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code = request.getParameter("code");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String author = request.getParameter("author");
		String stock = request.getParameter("stock");
		String publisher = request.getParameter("publisher");
		String description = request.getParameter("description");
		Book book = new Book();
		book.setCode(code);
		book.setName(name);
		book.setPrice(new BigDecimal(price));
		book.setAuthor(author);
		book.setStock(Integer.valueOf(stock));
		book.setPublisher(publisher);
		book.setDescription(description);

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		Result result = null;

		// 判断编号是否已经存在，如果已经存在，不允许新增
		BookService bookService = new BookServiceImpl();
		Book hasBook = bookService.getBookByCode(code);

		if (hasBook == null) {
			System.out.println("书籍不存在，可以新增");
			// 没有相同编号的书籍，可以新增
			bookService.addBook(book);
			result = Result.success("新增成功");
		} else {
			// 已存在相同编号的书籍，不能新增
			System.out.println("新增失败，该书籍编号已重复。");
			result = Result.error("新增失败，该书籍编号已重复。");
		}
		// 返回JSON数据给前端
		JSONObject json = (JSONObject) JSONObject.toJSON(result);
		writer.print(json);
		writer.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
